package com.hpf.tool.redis.interfaces.abstracts;

import javax.annotation.Resource;

import com.hpf.tool.interfaces.ICallable;
import com.hpf.tool.redis.exceptions.HJedisException;
import com.hpf.tool.redis.utils.HJedisPool;

import redis.clients.jedis.Jedis;
/**
 * 
 * @author hpf
 *
 */
public abstract class AHBaseJedis {
	@Resource
	private HJedisPool jedisPool;
	/**
	 * 从 对象池 获取 jedis 对象
	 * 
	 * @return Jedis
	 */
	private Jedis getJedis() {
		return jedisPool.getJedis();
	}
	
	/**
	 * 释放 Jedis
	 * @param jedis
	 */
	private void returnResource(final Jedis jedis){
		if(null != jedis){ 
			jedisPool.returnResource(jedis);
		}
	}
	
	/**
	 * 执行 Jedis
	 * @param call
	 * @return
	 */
	protected <O> O callBack(ICallable.ICallableIO<Jedis, O> call){
		Jedis jedis = this.getJedis();
		try {
			return call.exce(jedis);
		} catch (HJedisException ex) {
			throw ex;
		} catch (Exception ex) {
			throw new HJedisException(true,ex);
		} finally {
			this.returnResource(jedis);
		}
	}
	
	/**
	 * 执行 Jedis
	 * @param call
	 * @return
	 */
	protected void callBack(ICallable.ICallableI<Jedis> call){
		Jedis jedis = this.getJedis();
		try {
			call.exce(jedis);
		} catch (HJedisException ex) {
			throw ex;
		} catch (Exception ex) {
			throw new HJedisException(true,ex);
		} finally {
			this.returnResource(jedis);
		}
	}
	
	/**
	 * 校验 key
	 * @param key
	 */
	protected void verifyKey(final String key){
		if(key == null || "".equals(key)){
			throw new HJedisException(false,"key is empty.");
		}
	}
}
